package cn.tedu.straw.gateway.security;


import cn.tedu.straw.commons.security.LoginUserInfo;
import cn.tedu.straw.gateway.service.IUserService;
import cn.tedu.straw.gateway.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    IUserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名得到用户的详情
        //假设允许登录的用户名是admin，密码原文是123456
        if(username == null ){
            return null;
        }
        UserLoginVO userLoginVO = userService.getLoginUserInfo(username);
        if(userLoginVO == null){
            return null;
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(int i = 0; i<userLoginVO.getPermissions().size();i++){
            String authority = userLoginVO.getPermissions().get(i).getAuthority();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authority);
            authorities.add(simpleGrantedAuthority);
        }
        LoginUserInfo loginUserInfo = new LoginUserInfo(
                userLoginVO.getPhone(),
                userLoginVO.getPassword(),
                userLoginVO.getIsEnabled() == 1,
                true,
                true,
                userLoginVO.getIsLocked() == 0,
                authorities
        );
        loginUserInfo.setNickName(userLoginVO.getNickName());
        loginUserInfo.setId(userLoginVO.getId());

        loginUserInfo.setPhone(userLoginVO.getPhone());
        loginUserInfo.setAccounType(userLoginVO.getAccountType());
        return loginUserInfo;
    }
}
